from Acquisition import aq_inner
from Products.Five.browser import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile

from Products.CMFCore.utils import getToolByName

from apkn.resource.config import RESOURCETYPES, RESOURCECOUNTRIES
from apkn.resource.interfaces import IResourceFolder
from apkn.resource.interfaces import IResource


from plone.memoize.instance import memoize 

class ResourceFolderView(BrowserView):
    """Default view of a resource folder
    """

    def have_resources(self):
        return len(self.getItemsByCountry()) > 0

    def country_value(self):
        country = u""
        if self.request.has_key('country'):
            country =  RESOURCECOUNTRIES.getValue(self.request['country']) 
        return country


    @memoize    
    def getItemsByCountry(self):
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')       
        if self.request.has_key('country'):
            country = self.request['country'] 
        else:
            country=''
        search_path = '/'.join(context.getPhysicalPath())
        catalog_query = {
                        'object_provides': IResource.__identifier__,
                        'path':dict(query = search_path, depth = 1),
                        'resourcecountry':country
                        }

        brains = catalog(catalog_query)            
        if not brains:
            # bypass language filter
            catalog_query['Language']=''
            brains = catalog(catalog_query)
        resources = {}

        for resource in brains:
            if not resources.has_key(resource.resourcetype):
                resources[resource.resourcetype] = []
            resources[resource.resourcetype].append(dict(url=resource.getURL(),
                                                         title= str(resource.country).replace("-", " ").title() + " - " + str(resource.Title) ,))                                                       
        return sorted(resources.items()) 

    def resourcetypes(self):
        context = aq_inner(self.context)
        context_path = '/'.join(context.getPhysicalPath())
        catalog = getToolByName(context, 'portal_catalog') 
        resourcetypes ={}
        resources_here = catalog(path = context_path,
                                object_provides=IResource.__identifier__)
        resourcetypes_here = \
        [res.resourcetype for res in resources_here]
        resourcetype_values = list(set(resourcetypes_here))
        
        for resourcetype in resourcetype_values:
            resourcetypes[resourcetype] = RESOURCETYPES.getValue(resourcetype)
        return sorted(resourcetypes.items())                         


    def getItemsByResourcetype(self, **kwargs):
        """Get all items to list, by type. Returns a list of dicts:

        'id'      : A normalised string representing the section
        'section' : The name of the section
        'title'   : The title of the section - (caters for items with no section)
        'items'   : A list of catalog brains for items in this section

        The first item will have an section title of 'No section' and contain
        all items with no section selected.
        """
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')
        if self.request.has_key('resourcetype'):
            resourcetype = self.request['resourcetype'] 
        else:
            resourcetype=''
        search_path = '/'.join(context.getPhysicalPath())
        catalog_query = {
                        'object_provides': IResource.__identifier__,
                        'path': dict(query=search_path, depth=1),
                        'resourcetype': resourcetype                        
                        }
        # 'sort_on': 'resourcesubject' Disabled from the query above.
        
        brains = catalog(catalog_query)

        if not brains:
            #skip language check
            catalog_query['Language'] = ''
            brains = catalog(catalog_query)

        # Set up the dictionaries listing all sections
        sections = []

        sections.append({'id'       : 'no-section',
                         'section'  : 'No category',
                         'title' : 'No category',
                         'items'    : {}})

        for s in RESOURCETYPES.items():
            sections.append({'id'      : s[0],
                             'section' : s[0],
                             'title' : s[1],
                             'items'   : {}})   

        # Then insert each country and its resources in the appropriate section
        for b in brains:
            if b.resourcetype:
                itemSections = b.resourcetype
            else:
                itemSections = ['No category']
            matchedSections = [s for s in sections if s['section'] in itemSections]
            for s in matchedSections:
                country_value = RESOURCECOUNTRIES.getValue(b.country)
                if not s['items'].has_key(country_value):
                    s['items'][country_value] = []
                s['items'][country_value].append(b)                

        # Finally clean out empty sections

        delSections = []
        for j in range(len(sections)):
            if len(sections[j]['items']) == 0:
                delSections.append(j)
        delSections.reverse()
        for j in delSections:
            del sections[j]  
        return sections            
